
import { query } from "express"
import p from "./client.js"
import { z } from "zod"

const department_schema = z.object({
    name: z.string().min(2,"The name must be at least 2 characters long!"),
    email: z.string().email("The email is not valid!"),
    telephone: z.string()
}).passthrough().superRefine(async (data,ctx)=>{
    const nc = await p.department.count({
        where: {name: data.name}
    })
    if(nc>0){
        ctx.addIssue({
            path: ["name"],
            message: "The name must be unique!"
        })
    }
    const ec = await p.department.count({
        where: {email: data.email}
    })
    if(ec>0){
        ctx.addIssue({
            path: ["email"],
            message: "The email must be unique!"
        })
    }
})

const p1 = p.$extends({
    query: {
        department: {
            async create({args,query}){
                args.data = await department_schema.parseAsync(args.data)
                return query(args)
            },
            async createMany({args,query}){
                args.data = await Promise.all(args.data.map(async (d)=>await department_schema.parseAsync(d)))
                return query(args)
            },
            async update({args,query}){
                args.data = await department_schema.partial().parseAsync(args.data)
                return query(args)
            },
            async updateMany({args,query}){
                args.data = await department_schema.partial().parseAsync(args.data)
                return query(args)
            },
            async upsert({args,query}){
                args.create = await department_schema.parseAsync(args.create)
                args.update = await department_schema.partial().parseAsync(args.update)
                return query(args)
            }

        },
        club: {
            
        }
    }
})

export default p1